package top.jacktgq.sxt.bio.udp.demo4;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * @Author CandyWall
 * @Date 2019/10/20--18:51
 * @Description UDP引用类型接收端：
 *                     1、使用DatagramSocket指定端口 创建接收端
 *                     2、准备容器 封装成DatagramPacket包裹
 *                     3、阻塞式接收包裹receive(DatagramPacket p)
 *                     4、分析数据 将字节数组还原为基本类型
 *                      byte[] getData()
 *                             getLenth()
 *                     5、释放资源
 */
public class UDPTypeServer {
    public static void main(String[] args) throws Exception{
        System.out.println("接收方启动中...");
        //1、使用DatagramSocket指定端口 创建接收端
        DatagramSocket server = new DatagramSocket(9999);
        //2、准备容器 封装成DatagramPacket包裹
        byte[] container = new byte[1024*60];
        DatagramPacket packet = new DatagramPacket(container, 0, container.length);
        //3、阻塞式接收包裹receive(DatagramPacket p)
        server.receive(packet);
        //4、分析数据 byte[] getData() getLenth()
        byte[] data = packet.getData();
        int len = packet.getLength();
        //顺序与写出一致
        DataInputStream dis = new DataInputStream(new BufferedInputStream(new ByteArrayInputStream(data, 0, len)));
        String strValue = dis.readUTF();
        int intValue = dis.readInt();
        double doubleValue = dis.readDouble();
        boolean booleanValue = dis.readBoolean();
        char charValue = dis.readChar();
        System.out.println(
                "strValue:" + strValue + "\n" +
                "intValue:" + intValue + "\n" +
                "doubleValue:" + doubleValue + "\n" +
                "booleanValue:" + booleanValue + "\n" +
                "charValue:" + charValue  + "\n"
        );

        //5、释放资源
        dis.close();
        server.close();
    }
}
